﻿namespace Digitalmes.Application.Sys.Menus.Queries;

/// <summary>
/// 按树结构查询菜单命令。
/// </summary>
public record GetMenuListWithTreeQuery(string? Title, EnabledStatusEnum? Status) : IRequest<IResult<List<SysMenuDto>>>;

internal sealed class GetMenuListWithTreeQueryHandler(IRepository<SysMenu> repo) : IRequestHandler<GetMenuListWithTreeQuery, IResult<List<SysMenuDto>>>
{
    public async Task<IResult<List<SysMenuDto>>> Handle(GetMenuListWithTreeQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(request.Title), m => m.Title.Contains(request.Title!))
            .WhereIF(request.Status.HasValue, m => m.Status == request.Status)
            .ToTreeAsync(m => m.Children, m => m.ParentId, 0, m => m.Id);
        return Result.From(items.Adapt<List<SysMenuDto>>());
    }
}
